package cn.devzyh.oms.common.security.feign;

import cn.devzyh.oms.common.core.constant.SecurityConstants;
import cn.devzyh.oms.common.core.util.WebUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;

import java.util.Collection;
import java.util.Optional;

/**
 * oauth2 feign token传递
 * <p>
 * 重新 OAuth2FeignRequestInterceptor ，官方实现部分常见不适用
 *
 * @author lengleng
 * @date 2022/5/29
 */
@Slf4j
@RequiredArgsConstructor
public class OmsOAuthRequestInterceptor implements RequestInterceptor {

	private final BearerTokenResolver tokenResolver;

	/**
	 * Feign传递参数处理
	 *
	 * @param template
	 */
	@Override
	public void apply(RequestTemplate template) {
		HttpServletRequest request = null;
		Optional<HttpServletRequest> optional = WebUtils.getRequest();
		if (optional.isPresent()) {
			request = WebUtils.getRequest().get();
		}

		// 本地调试参数
		if (request != null) {
			template.header(SecurityConstants.DEBUG, request.getHeader(SecurityConstants.DEBUG));
		}

		// 内部调用参数
		Collection<String> fromHeader = template.headers().get(SecurityConstants.FROM);
		if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstants.FROM_IN)) {
			return;
		}

		// 身份验证Token
		if (request == null) {
			return;
		}
		String token = tokenResolver.resolve(request);
		if (StrUtil.isBlank(token)) {
			return;
		}
		template.header(HttpHeaders.AUTHORIZATION,
				String.format("%s %s", OAuth2AccessToken.TokenType.BEARER.getValue(), token));
	}

}
